package bean;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.annotation.PostConstruct;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;
import javax.faces.context.FacesContext;
import javax.inject.Inject;

import dao.DoctorDAO;
import dao.DoctorSpecialtyDAO;
import dao.JPA;
import entity.Doctor;
import entity.Role;

@ManagedBean
@ViewScoped
public class SelectDoctorBean {

	@Inject @JPA
    private DoctorDAO doctorDAO;	
	@Inject @JPA
    private DoctorSpecialtyDAO doctorSpecialtyDAO;	
	private List<Doctor> resultList;
	private List<String> doctorSpecialtyList = new ArrayList<>();
	private String selectedSpec;
	private String cid;
	private Role doctorRole = new Role("Doctor"); 
	
	@PostConstruct
	private void init() {
		Map<String, String> params = FacesContext.getCurrentInstance().getExternalContext().getRequestParameterMap();
		cid = params.get("cid");		
		doctorSpecialtyList.add("All");
		doctorSpecialtyList.addAll(doctorSpecialtyDAO.selectDoctorSpecialtyNames());
		selectedSpec = "All";
		getDoctorListBySpecialty();
	}
	
	public void getDoctorListBySpecialty() {		
		if(selectedSpec.equals("All")) {			
			resultList = doctorDAO.findAll();			
		} else resultList = doctorDAO.selectDoctorListBySpecialtyName(selectedSpec);
		removeDoctorsWithoutRole();
	}
	
	private void removeDoctorsWithoutRole() {	
		Iterator<Doctor> iter = resultList.iterator();
		while(iter.hasNext()) {
			if(!iter.next().getUser().getRoles().contains(doctorRole))
				iter.remove();
		}
	}
	
	public List<Doctor> getResultList() {	
		return resultList;
	}

	public List<String> getDoctorSpecialtyList() {
		return doctorSpecialtyList;
	}

	public String getSelectedSpec() {
		return selectedSpec;
	}

	public void setSelectedSpec(String selectedSpec) {
		this.selectedSpec = selectedSpec;
	}
	
	public String goBack() {
		return "createTreatmentRequest.xhtml?cid=" + cid + "&faces-redirect=true";
	}
	
}
